package libx

import (
	"sync"

	slt "gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

type _Sqlite struct {
	db *gorm.DB
}

func (s *_Sqlite) DB() *gorm.DB {
	return s.db
}

func (s *_Sqlite) setup(path string) error {
	var err error
	s.db, err = gorm.Open(slt.Open(path), &gorm.Config{})
	return err
}

var sqlites map[string]*_Sqlite = make(map[string]*_Sqlite)
var sqlite_mu sync.Mutex

func AddSqlite(name string, path string) error {
	sqlite_mu.Lock()
	defer sqlite_mu.Unlock()
	if _, ok := sqlites[name]; ok {
		return nil
	}
	sqlite := &_Sqlite{}
	err := sqlite.setup(path)
	if err != nil {
		return err
	}
	sqlites[name] = sqlite
	return nil
}

func Sqlite(name string) (*_Sqlite, error) {
	sqlite_mu.Lock()
	defer sqlite_mu.Unlock()
	if sqlite, ok := sqlites[name]; ok {
		return sqlite, nil
	}
	sqlite := &_Sqlite{}
	err := sqlite.setup(name)
	if err != nil {
		return nil, err
	}
	return sqlite, nil
}
